
# coding=utf-8

from io import StringIO
import os
from os.path import join
import shutil
from typing import Tuple

def removeSpace(data:str)->str:
    return "NA" if data.strip() == "" else data.strip()

def complete_type(type:str)->str:
    if type.startswith("uint32"):
        return "uint32_t"
    elif type.startswith("int32"):
        return "int32_t"
    elif type.startswith("uint8"):
        return "uint8_t"
    elif type.startswith("int8"):
        return "int8_t"
    elif type.startswith("uint16"):
        return "uint16_t"
    elif type.startswith("int16"):
        return "int16_t"
    elif type.startswith("int64"):
        return "int64_t"
    elif type.startswith("uint64"):
        return "uint64_t"
    else:
        raise Exception("暂不支持自定义结构体成员类型{}".format(type))


def writeFile(file_path,file_name,callback):
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    with open(join(file_path,file_name),"w") as f:
        callback(f)

def writeFileAppend(file_path,file_name,callback):
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    with open(join(file_path,file_name),"a+") as f:
        callback(f)


def errorFn(info:str):
    raise RuntimeError(info)

def parseEncodeName(type_name:str)->Tuple[str,bool]:
    if type_name.startswith("struct_"):
        return (type_name[len("struct_"):],True)
    elif type_name.startswith("enum_"):
        return (type_name[len("enum_"):],False)
    else:
        raise Exception("未知类型: {0}".format(type_name))

def parseCustomData(isStruct:bool,members:str,fn):
    with StringIO(members) as ios:
        for line in [line.strip() for line in ios.readlines()]:
            if isStruct:
                properties = line.split(";")
                for property in [property for property in properties if property != ""]:
                    (p_type, name) = property.split(" ")
                    fn("{} {}".format(
                        complete_type(p_type.strip().lower()), name))
            else:
                properties = line.split(",")
                for property in [property for property in properties if property != ""]:
                    fn(property)

def copyPackageTo(src,dest):
    if os.path.exists(dest):
        shutil.rmtree(dest)
    shutil.copytree(src, dest)
    removeDir(src)

def removeDir(dir):
    if os.path.exists(dir):
        shutil.rmtree(dir)